package com.xiong.springsecurity.filter;

import com.xiong.springsecurity.service.impl.LoginUser;
import com.xiong.springsecurity.utils.JwtUtil;
import com.xiong.springsecurity.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * <p>
 *
 * @author XiongDa
 * @version 1.0.0
 * @belongsProject: SpringSecurity
 * @belongsPackage: com.xiong.springsecurity.filter
 * @since 2023/6/14 15:18
 **/
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse, @NotNull FilterChain filterChain) throws ServletException, IOException {
        // 1. 获取 token
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)){
            // 没有token跳过此过滤器, 交给后面的过滤器处理 如登入接口
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            // 由于没有token, 当过滤器返回时, 下面代码也不需要执行, 所以return
            return;
        }

        //2. 解析 token
        String userId;
        try {
            userId = JwtUtil.parseJWT(token).getSubject();
            log.info("当前用户token携带的id: {}", userId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // 3. redis获取用户信息
        // todo redis的key不能用用户id, 因为多次登入生成的token, 解析后获取的用户id都一样, 这样导致多个token都有效
        // 建议随机生成key 存 token 里, 且作为redis的key
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
        log.info("当前用户loginUser对象信息: {}", loginUser);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登入");
        }

        // 4. 存入SecurityContextHolder, 用作登入后的认证
        Authentication authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
